﻿using HXDNB.DAL;
using HXDNB.Infrastructure;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace HXDNB.CMS.Controllers
{
    public class TemplateController : BaseController
    {
        //
        // GET: /Template/

        public ViewResult Index(int index = 0)
        {
            using (var tb = new TemplateBLL())
            {
                ViewBag.PagList = new Paging<Template>(index, tb.Select().AsQueryable(), 50);
            }

            return View();
        }

        /// <summary>
        /// 模版信息
        /// </summary>
        public ViewResult Info(int? id)
        {
            try
            {
                ViewBag.Templates = GetTemplates();

                if (id.HasValue)
                {
                    using (var tb = new TemplateBLL())
                        return View(tb.Get(id.Value));
                }
            }
            catch (Exception ex)
            {
                Infrastructure.Log.Error("TemplateController.Info", ex.Message + ex.StackTrace);
            }

            return View(new Template { IsRelease = "N" });
        }

        /// <summary>
        /// 模版信息
        /// </summary>
        [HttpPost]
        public ViewResult Info(Template model)
        {
            try
            {
                ViewBag.Templates = GetTemplates();

                model.Path = @"/Temp/" + model.Name;
                using (var tb = new TemplateBLL())
                {
                    if (model.Id > 0)
                        ViewBag.Result = tb.Edit(model);
                    else
                    {
                        model.IsRelease = "N";
                        ViewBag.Result = tb.Add(model) > 0;
                    }
                }
            }
            catch (Exception ex)
            {
                ViewBag.Result = false;
                Infrastructure.Log.Error("TemplateController.Info[HttpPost]", ex.Message + ex.StackTrace);
            }

            return View();
        }

        /// <summary>
        /// 模版内容编辑
        /// </summary>
        public ViewResult Edit(int id)
        {
            try
            {
                using (var tb = new TemplateBLL())
                {
                    var temp = tb.Get(id);
                    var path = Server.MapPath(temp.Path);
                    ViewBag.Content = System.IO.File.ReadAllText(path, System.Text.Encoding.UTF8);
                    ViewBag.Id = id;
                }
            }
            catch (Exception ex)
            {
                ViewBag.Content = "";
                Infrastructure.Log.Error("TemplateController.Edit", ex.Message + ex.StackTrace);
            }

            return View();
        }

        /// <summary>
        /// 保存模版内容
        /// </summary>
        public ContentResult Save(int id, string content)
        {
            try
            {
                using (var tb = new TemplateBLL())
                {
                    var temp = tb.Get(id);
                    var path = Server.MapPath(temp.Path);
                    var bak = Config.Template + @"/Bak";
                    //备份原文件
                    if (!Directory.Exists(bak))
                        Directory.CreateDirectory(bak);
                    System.IO.File.Copy(path, bak + @"/" + temp.Name + "." + DateTime.Now.ToString("yyyyMMddHHmmss") + ".bak");
                    System.IO.File.WriteAllText(path, HttpUtility.UrlDecode(content), System.Text.Encoding.UTF8);

                    temp.IsRelease = "N";
                    tb.Edit(temp);
                }

                return Content("Ok");
            }
            catch (Exception ex)
            {
                Infrastructure.Log.Error("TemplateController.Save", ex.Message + ex.StackTrace);
                return Content("Error");
            }
        }

        /// <summary>
        /// 删除模版
        /// </summary>
        public ContentResult Delete(int id)
        {
            try
            {
                using (var tb = new TemplateBLL())
                    tb.Delete(id);
                return Content("Ok");
            }
            catch (Exception ex)
            {
                Infrastructure.Log.Error("TemplateController.Delete", ex.Message + ex.StackTrace);
                return Content("Error");
            }
        }

        /// <summary>
        /// 获取模板文件集合
        /// </summary>
        private IEnumerable<SelectListItem> GetTemplates()
        {
            var folder = new DirectoryInfo(Server.MapPath(@"~/Temp/"));
            var list = folder.GetFiles();
            return list.Select(f => new SelectListItem { Text = f.Name, Value = f.Name });
        }
    }
}
